package com.mall.b2c.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContextException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.mall.b2c.domain.goods.BrandDomain;
import com.mall.b2c.service.BrandService;
import com.mall.b2c.util.JsonDataGridHelper;
import com.mall.common.bean.Order;
import com.mall.common.bean.Pager;
import com.mall.common.bean.SearchFilter;
import com.mall.common.controller.BaseController;
import com.mall.common.exception.NoticeException;
import com.mall.common.util.ResponseUtils;
import com.mall.common.validation.annotation.IntRangeFieldValidator;
import com.mall.common.validation.annotation.RequiredFieldValidator;
import com.mall.common.validation.annotation.RequiredStringValidator;
import com.mall.common.validation.annotation.Validations;
import com.mall.common.web.Servlets;

/**
 * 品牌
 */
@Controller
@RequestMapping("/admin/b2c/brand")
public class BrandController  extends BaseController{
	@Resource private BrandService brandService;
	
	@RequestMapping("/checkBrandName")
	@ResponseBody
	public String checkBrandName(String oldName, @RequestParam("name") String newName) {
		if(brandService.isUnique("name", oldName, newName)) {
			return "true";
		} else {
			return "false";
		}
	}
	
	/**
	 * 跳转到列表页面
	 */
	@RequestMapping(value="/list", method=RequestMethod.GET)
	public String list(Model model){
		return "/admin/b2c/brand/list";
	}

	/**
	 * 获取列表信息
	 */
	@RequestMapping(value="/queryData", method=RequestMethod.POST)
	@ResponseBody
	public Pager queryData(Pager pager, HttpServletRequest request){
    	Map<String, Object> filterParams = Servlets.getParametersStartingWith(request);
		List<SearchFilter> filters = SearchFilter.parse(filterParams);
		pager.addOrder(Order.desc("id"));
    	pager = brandService.findPage(pager, filters);
		return JsonDataGridHelper.createJSONData(pager);
    }
	
    /**
	 * 跳转到新增页面
	 */
	@RequestMapping(value="/add", method=RequestMethod.GET)
	public String input(Model model){
		return "/admin/b2c/brand/input";
	}
	
	/**
	 * 保存
	 */
	@Validations(
		requiredStrings = {
			@RequiredStringValidator(fieldName = "name", message = "品牌不允许为空!")
		},
		requiredFields = { 
			@RequiredFieldValidator(fieldName = "priority", message = "排序不允许为空!")
		},
		intRangeFields = {
			@IntRangeFieldValidator(fieldName = "priority", min = "0", message = "排序必须为零或正整数!")
		}
	)
	@RequestMapping(value="/save", method=RequestMethod.POST)
	public String save(BrandDomain brand, Model model, HttpServletResponse response){
		if(!brandService.isUnique("name", null, brand.getName())) {
			throw new NoticeException("品牌名称已存在!");
		}
		brandService.persist(brand);
		return ResponseUtils.renderJSON(successMessage, response);
    }
    
	/**
	 * 编辑
	 */
	@Validations(
		requiredFields = { 
			@RequiredFieldValidator(fieldName = "id", message = "ID非法!")
		}
	)
	@RequestMapping(value="/edit", method=RequestMethod.GET)
	public String edit(Long id, Model model){
		BrandDomain brand = brandService.find(id);
    	model.addAttribute("brand", brand);
		return "/admin/b2c/brand/input";
	}
	
	/**
	 * 修改
	 */
	@Validations(
		requiredStrings = {
			@RequiredStringValidator(fieldName = "name", message = "品牌不允许为空!")
		},
		requiredFields = { 
			@RequiredFieldValidator(fieldName = "priority", message = "排序不允许为空!")
		},
		intRangeFields = {
			@IntRangeFieldValidator(fieldName = "priority", min = "0", message = "排序必须为零或正整数!")
		}
	)
	@RequestMapping(value="/update", method=RequestMethod.POST)
	@ResponseBody
	public String update(BrandDomain brand, HttpServletResponse response){
		BrandDomain currentBrand = brandService.find(brand.getId());
		if(currentBrand == null) {
			throw new NoticeException("当前品牌不存在!");
		}
		if(!brandService.isUnique("name", currentBrand.getName(), brand.getName())) {
			throw new NoticeException("品牌名称已存在!");
		}
		brandService.updateByUpdater(brand);
		return ResponseUtils.renderJSON(successMessage, response);
	}
	
    /**
	 * 删除品牌
	 */
	@Validations(
		requiredFields = {
			@RequiredFieldValidator(fieldName = "ids", message = "ids非法")	
		}
	)
	@RequestMapping(value="/delete", method=RequestMethod.POST)
	@ResponseBody
	public String delete(Long[] ids, HttpServletResponse response){
		brandService.remove(ids);
    	return ResponseUtils.renderJSON(successMessage, response);
    }
	
	/**
	 * 导入品牌与商品的关联关系
	 * @return
	 */
	@RequestMapping("/import")
	public String importBrandInfo(@RequestParam(value = "importFile", required = true) MultipartFile multipartFile, 
			String type, HttpServletResponse response){
		String filename = multipartFile.getOriginalFilename();  
        if(filename == null || (!filename.endsWith(".xls") && !filename.endsWith(".xlsx"))){  
            return ResponseUtils.renderText("文件格式不正确", response);
        }  
		try {
			brandService.importBrandInfo(type, multipartFile);
		} catch (Exception e) {
			if(e instanceof ApplicationContextException){
				return ResponseUtils.renderText(e.getMessage(), response);
			}
			return ResponseUtils.renderText("导入出错", response);
		}
		return ResponseUtils.renderText("导入成功", response);
	}
}
